/**
 * 拼单功能服务
 * 基于后端拼单管理接口实现
 * 
 * 接口文档参考: FRONTEND_QUICK_START.md
 */

import http from './api.js'

// 拼单活动状态映射
const GROUP_BUYING_STATUS = {
    active: '拼单中',
    success: '拼单成功',
    failed: '拼单失败',
    cancelled: '已取消'
}

// 参与者状态映射
const PARTICIPANT_STATUS = {
    joined: '已参与',
    paid: '已支付',
    cancelled: '已取消'
}

// 拼单服务
const groupBuyingService = {
    /**
     * 获取拼单活动列表
     * GET /api/v1/group-buying
     * 
     * @param {Object} params 查询参数
     * @param {String} params.status - 活动状态筛选 (active/success/failed/cancelled)
     * @param {String} params.keyword - 搜索关键词
     * @param {Boolean} params.hot - 是否热门
     * @param {Number} params.page - 页码（默认1）
     * @param {Number} params.limit - 每页数量（默认20）
     */
    getActivityList: async (params = {}) => {
        try {
            const queryParams = {
                page: params.page || 1,
                limit: params.limit || 20
            }

            // 添加可选参数
            if (params.status) queryParams.status = params.status
            if (params.keyword) queryParams.keyword = params.keyword
            if (params.hot !== undefined) queryParams.hot = params.hot

            console.log('获取拼单活动列表 - 查询参数:', queryParams)

            const response = await http.get('/group-buying', queryParams)

            console.log('获取拼单活动列表 - 响应:', response)
            return response
        } catch (error) {
            console.error('获取拼单活动列表失败:', error)
            throw error
        }
    },

    /**
     * 获取拼单活动详情
     * GET /api/v1/group-buying/{id}
     * 
     * @param {Number} activityId 拼单活动ID
     */
    getActivityDetail: async (activityId) => {
        try {
            console.log('获取拼单活动详情 - 活动ID:', activityId)

            const response = await http.get(`/group-buying/${activityId}`)

            console.log('获取拼单活动详情 - 响应:', response)
            return response
        } catch (error) {
            console.error('获取拼单活动详情失败:', error)
            throw error
        }
    },

    /**
     * 创建拼单活动
     * POST /api/v1/group-buying
     * 
     * @param {Object} activityData 拼单活动数据
     * @param {Number} activityData.foodId - 商品ID
     * @param {String} activityData.title - 拼单标题
     * @param {String} activityData.description - 拼单描述
     * @param {Number} activityData.minParticipants - 最少参与人数
     * @param {Number} activityData.maxParticipants - 最多参与人数
     * @param {Number} activityData.groupPrice - 拼团价
     * @param {Number} activityData.durationHours - 持续时间（小时）
     * @param {Number} activityData.quantity - 购买数量
     * @param {String} activityData.spiceLevel - 辣度选择
     */
    createActivity: async (activityData) => {
        try {
            console.log('创建拼单活动 - 请求数据:', activityData)

            const response = await http.post('/group-buying', {
                foodId: activityData.foodId,
                title: activityData.title,
                description: activityData.description || '',
                minParticipants: activityData.minParticipants,
                maxParticipants: activityData.maxParticipants,
                groupPrice: activityData.groupPrice,
                durationHours: activityData.durationHours || 24,
                quantity: activityData.quantity || 1,
                spiceLevel: activityData.spiceLevel || '不辣'
            }, {
                needAuth: true,
                showLoading: true,
                loadingText: '创建拼单中...'
            })

            console.log('创建拼单活动 - 响应:', response)
            return response
        } catch (error) {
            console.error('创建拼单活动失败:', error)
            throw error
        }
    },

    /**
     * 参与拼单
     * POST /api/v1/group-buying/{id}/join
     * 
     * @param {Number} activityId 拼单活动ID
     * @param {Object} joinData 参与数据
     * @param {Number} joinData.quantity - 购买数量
     * @param {String} joinData.spiceLevel - 辣度选择
     */
    joinActivity: async (activityId, joinData) => {
        try {
            console.log('参与拼单 - 活动ID:', activityId, '参与数据:', joinData)

            const response = await http.post(`/group-buying/${activityId}/join`, {
                quantity: joinData.quantity || 1,
                spiceLevel: joinData.spiceLevel || '不辣'
            }, {
                needAuth: true,
                showLoading: true,
                loadingText: '参与拼单中...'
            })

            console.log('参与拼单 - 响应:', response)
            return response
        } catch (error) {
            console.error('参与拼单失败:', error)
            throw error
        }
    },

    /**
     * 退出拼单（参与者）
     * DELETE /api/v1/group-buying/{id}/leave
     * ✅ 已对接后端接口
     * 
     * @param {Number} activityId 拼单活动ID
     */
    leaveActivity: async (activityId) => {
        try {
            console.log('退出拼单 - 活动ID:', activityId)

            const response = await http.delete(`/group-buying/${activityId}/leave`, {}, {
                needAuth: true,
                showLoading: true,
                loadingText: '退出拼单中...'
            })

            console.log('退出拼单 - 响应:', response)
            return response
        } catch (error) {
            console.error('退出拼单失败:', error)
            throw error
        }
    },

    /**
     * 取消拼单活动（发起人专用）
     * PUT /api/v1/group-buying/{id}/cancel
     * ✅ 已对接后端接口
     * 
     * @param {Number} activityId 拼单活动ID
     * @param {String} reason 取消原因（可选）
     */
    cancelActivity: async (activityId, reason = '') => {
        try {
            console.log('取消拼单活动 - 活动ID:', activityId, '原因:', reason)

            const response = await http.put(`/group-buying/${activityId}/cancel`, {
                reason
            }, {
                needAuth: true,
                showLoading: true,
                loadingText: '取消拼单中...'
            })

            console.log('取消拼单活动 - 响应:', response)
            return response
        } catch (error) {
            console.error('取消拼单活动失败:', error)
            throw error
        }
    },

    /**
     * 获取我的拼单参与列表
     * GET /api/v1/group-buying/my-participations
     */
    getMyParticipations: async () => {
        try {
            console.log('获取我的拼单参与列表')

            const response = await http.get('/group-buying/my-participations', {}, {
                needAuth: true
            })

            console.log('获取我的拼单参与列表 - 响应:', response)
            return response
        } catch (error) {
            console.error('获取我的拼单参与列表失败:', error)
            throw error
        }
    },

    /**
     * 获取活动参与者列表
     * GET /api/v1/group-buying/{id}/participants
     * 
     * @param {Number} activityId 拼单活动ID
     */
    getParticipants: async (activityId) => {
        try {
            console.log('获取活动参与者列表 - 活动ID:', activityId)

            const response = await http.get(`/group-buying/${activityId}/participants`)

            console.log('获取活动参与者列表 - 响应:', response)
            return response
        } catch (error) {
            console.error('获取活动参与者列表失败:', error)
            throw error
        }
    },

    /**
     * 获取活动状态文本
     * @param {String} status 活动状态
     */
    getStatusText: (status) => {
        return GROUP_BUYING_STATUS[status] || '未知状态'
    },

    /**
     * 获取参与者状态文本
     * @param {String} status 参与者状态
     */
    getParticipantStatusText: (status) => {
        return PARTICIPANT_STATUS[status] || '未知状态'
    },

    /**
     * 格式化拼单活动数据（用于列表展示）
     * @param {Object} activity 拼单活动对象
     */
    formatActivityForList: (activity) => {
        return {
            id: activity.id,

            // 发起人信息
            initiatorUserId: activity.initiator_user_id || activity.initiatorUserId,
            // 优先显示真实姓名，其次用户名，最后默认"发起人"
            initiatorName: activity.initiator_real_name || activity.initiatorRealName || 
                          activity.initiator_name || activity.initiatorName || 
                          activity.initiator_username || activity.initiatorUsername || '发起人',

            // 商品信息
            foodId: activity.food_id || activity.foodId,
            foodName: activity.food_name || activity.foodName || '商品',
            foodImage: activity.food_image || activity.foodImage || '/static/food1.jpg',

            // 商家信息
            merchantId: activity.merchant_id || activity.merchantId,
            merchantName: activity.merchant_name || activity.merchantName || '商家',
            deliveryFee: activity.delivery_fee || activity.deliveryFee || 0,  // ⭐ 配送费

            // 拼单信息
            title: activity.title,
            description: activity.description || '',
            minParticipants: activity.min_participants || activity.minParticipants || 2,
            maxParticipants: activity.max_participants || activity.maxParticipants || 10,
            currentParticipants: activity.current_participants || activity.currentParticipants || 1,

            // 价格信息
            originalPrice: activity.original_price || activity.originalPrice || 0,
            groupPrice: activity.group_price || activity.groupPrice || 0,

            // 时间信息
            startTime: activity.start_time || activity.startTime,
            endTime: activity.end_time || activity.endTime,

            // 状态
            status: activity.status,
            statusText: groupBuyingService.getStatusText(activity.status),

            // 计算进度百分比
            progress: Math.round(((activity.current_participants || activity.currentParticipants || 1) / (activity.max_participants || activity.maxParticipants || 2)) * 100),

            // 是否还有空位
            hasSlots: (activity.current_participants || activity.currentParticipants || 1) < (activity.max_participants || activity.maxParticipants || 2),

            // 创建时间
            createdAt: activity.created_at || activity.createdAt
        }
    },

    /**
     * 格式化拼单活动数据（用于详情展示）
     * @param {Object} activity 拼单活动对象
     */
    formatActivityDetail: (activity) => {
        const formatted = groupBuyingService.formatActivityForList(activity)

        // 添加详情页特有的字段
        return {
            ...formatted,

            // 参与者列表（过滤掉已取消的参与者）
            participants: (activity.participants || [])
                .filter(p => p.status !== 'cancelled')  // 只显示 joined 和 paid 状态的参与者
                .map((p, index) => ({
                    id: p.id,
                    userId: p.user_id || p.userId,
                    // 优先显示真实姓名，其次用户名，最后默认"用户"
                    userName: p.realName || p.real_name || p.user_name || p.userName || p.username || '用户',
                    userAvatar: p.avatar || p.user_avatar || p.userAvatar || '/static/avatar.jpg',
                    quantity: p.quantity || 1,
                    spiceLevel: p.spice_level || p.spiceLevel || '不辣',
                    status: p.status,
                    statusText: groupBuyingService.getParticipantStatusText(p.status),
                    // ⭐ 修复：所有参与者都使用 joined_at，如果为空则用活动创建时间作为 fallback
                    joinedAt: p.joined_at || p.joinedAt || activity.created_at || activity.createdAt
                })),

            // 是否是发起人
            isInitiator: false, // 需要在外部比对当前用户ID

            // 是否已参与
            isParticipated: false, // 需要在外部比对当前用户ID

            // 剩余时间（秒）
            remainingSeconds: 0, // 需要根据 endTime 计算

            // 剩余名额
            remainingSlots: (activity.max_participants || activity.maxParticipants || 2) - (activity.current_participants || activity.currentParticipants || 1)
        }
    },

    /**
     * 计算拼单剩余时间
     * @param {String} endTime 结束时间字符串
     * @returns {Object} { days, hours, minutes, seconds, isExpired }
     */
    calculateRemainingTime: (endTime) => {
        const now = new Date().getTime()
        const end = new Date(endTime).getTime()
        const diff = end - now

        if (diff <= 0) {
            return {
                days: 0,
                hours: 0,
                minutes: 0,
                seconds: 0,
                isExpired: true,
                text: '已结束'
            }
        }

        const days = Math.floor(diff / (1000 * 60 * 60 * 24))
        const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
        const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
        const seconds = Math.floor((diff % (1000 * 60)) / 1000)

        let text = ''
        if (days > 0) {
            text = `${days}天${hours}小时`
        } else if (hours > 0) {
            text = `${hours}小时${minutes}分钟`
        } else if (minutes > 0) {
            text = `${minutes}分钟${seconds}秒`
        } else {
            text = `${seconds}秒`
        }

        return {
            days,
            hours,
            minutes,
            seconds,
            isExpired: false,
            text
        }
    },

    /**
     * 检查是否可以参与拼单
     * @param {Object} activity 拼单活动对象
     * @param {Number} currentUserId 当前用户ID
     */
    canJoinActivity: (activity, currentUserId) => {
        // 检查状态
        if (activity.status !== 'active') {
            return { can: false, reason: '拼单活动已结束' }
        }

        // 检查是否已满
        if ((activity.current_participants || activity.currentParticipants || 0) >= (activity.max_participants || activity.maxParticipants || 2)) {
            return { can: false, reason: '拼单已满' }
        }

        // 检查是否过期
        const remaining = groupBuyingService.calculateRemainingTime(activity.end_time || activity.endTime)
        if (remaining.isExpired) {
            return { can: false, reason: '拼单已过期' }
        }

        // 检查是否已参与
        if (activity.participants && activity.participants.length > 0) {
            const participated = activity.participants.some(p =>
                (p.user_id || p.userId) === currentUserId &&
                p.status !== 'cancelled'
            )
            if (participated) {
                return { can: false, reason: '您已参与此拼单' }
            }
        }

        return { can: true, reason: '' }
    }
}

export default groupBuyingService

